package com.magic.service.impl;

import com.magic.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Slf4j
@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int saveUserCount(Integer userId) {
        //根据不同用户id生成调用次数的key
        String limitKey = "LIMIT"+"_"+userId;
        //获取redis中key 的调用次数
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);
        int limit = -1;
        if(limitNum == null){
            //第一次调用放入redis中设置为0
            stringRedisTemplate.opsForValue().set(limitKey,"0",3600, TimeUnit.SECONDS);
        }else{
            //不是第一次调用+1
            limit = Integer.parseInt(limitNum)+1;
            stringRedisTemplate.opsForValue().set(limitKey,String.valueOf(limit),3600,TimeUnit.SECONDS);
        }
        return limit;
    }

    @Override
    public boolean getUserCount(Integer userId) {
        //根据不同用户id生成调用次数的key
        String limitKey = "LIMIT"+"_"+userId;
        //获取redis中key 的调用次数
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);
        if(limitNum==null){
            //为空直接抛出key异常
            log.error("该用户没有申请验证值记录，疑似异常");
            return true;
        }

        return Integer.parseInt(limitNum) > 10;//false代表没有超过 true代表超过
    }
}
